package client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Observable;

import server.ISortFactory;
import server.ISorter;

/**
 * @author Rob
 *
 */
public class SorterThread extends Observable implements Runnable {

	private Comparable[] sortThisList;
	private Comparable[] sortedList;
	private int volgNummer;
	private Thread sortingThread;
	
	/**
	 * Initialize
	 * @param sortThisList	List to sort
	 * @param volgNummer	The threadnumber
	 * @param lj	The observer
	 */
	public SorterThread(Comparable[] sortThisList, int volgNummer, ListJoiner lj) {
		super();
		this.sortThisList = sortThisList;
		this.volgNummer = volgNummer;
		addObserver(lj);
	}
	
	/**
	 * Lookup the server and create new sorter. Then sort the list and notify the observer
	 */
	@Override
	public void run() {
		try {
			ISortFactory sf = (ISortFactory) Naming.lookup("//localhost:1099/sorting");
			ISorter sorter = sf.createSorter("server.QuickSort");
			sortedList = sorter.sort(sortThisList);
			setChanged();
			notifyObservers("List is sorted");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * return the sortedList
	 * @return sortedList
	 */
	public Comparable[] getSortedList() {
		return sortedList;
	}
	
	/**
	 * return the threadnunmber
	 * @return volgnummer
	 */
	public int getVolgNummer() {
		return volgNummer;
	}
	
	/**
	 * Start new thread with this and execute.
	 */
	public void sort() {
		sortingThread = new Thread(this);
		sortingThread.start();
	}
}
